package com.kumi.crowd.controller;


import com.github.pagehelper.PageInfo;
import com.kumi.crowd.bean.Admin;
import com.kumi.crowd.constant.CrowdConstant;
import com.kumi.crowd.service.AdminService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @RequestMapping("/login")
    public String login(@RequestParam("loginAcct") String loginAcc, @RequestParam("userPassword") String userPassword, HttpSession session) {
        Admin admin = adminService.getAdminByLoginAcct(loginAcc, userPassword);
        session.setAttribute(CrowdConstant.ATTR_NAME_LOGIN_ADMIN, admin);
        return "redirect:/admin/main";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/admin/login/page";
    }

    @RequestMapping("/pageInfo")
    public String getPage(
            @RequestParam(value = "keyword", defaultValue = "") String keyword,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
            ModelMap modelMap) {

        PageInfo<Admin> page = adminService.getPage(keyword, pageNum, pageSize);

        modelMap.addAttribute(CrowdConstant.ATTR_NAME_PAGE_INFO, page);

        return "user";
    }

    @RequestMapping("/remove")
    public String remove(
            @Param("id") Integer id,
            @Param("pageNum") Integer pageNum,
            @Param("keyword") String keyword) {
        adminService.remove(id);
        return "redirect:/admin/pageInfo?pageNum=" + pageNum + "&keyword=" + keyword;
    }

    @RequestMapping("/add")
    public String add(Admin admin){
        adminService.add(admin);
        return "redirect:/admin/pageInfo?pageNum=" + Integer.MAX_VALUE;
    }

    @RequestMapping("edit")
    public String edit(
            @Param("id") Integer id,
            ModelMap modelMap){

        System.out.println(id);
        Admin admin = adminService.getById(id);
        modelMap.addAttribute("admin",admin);
        return "edit";
    }

    @RequestMapping("update")
    public String update(
            Admin admin,
            @Param("pageNum") Integer pageNum){

        adminService.update(admin);

        return "redirect:/admin/pageInfo?pageNum=" + pageNum;

    }
}
